<template>
  <base-page-view class-name="page-container a-orderCheck-page">
    <view class="address-container">
      <view class="lineBox">
        <view class="adressLine">
          <view class="lable-L">手机号</view>
          <input v-model="addressData.mobile" class="input" type="number" placeholder="请输入手机号" placeholder-class="placeholder" maxlength="11" @blur="btnFixed()" />
        </view>
        <view class="adressLine">
          <view class="lable-L">验证码</view>
          <input v-model="addressData.code" class="input" type="number" placeholder="请输入验证码" placeholder-class="placeholder" maxlength="6" />
          <view class="verifyBox" @click="verify">
            {{ getVerify }}
          </view>
        </view>
        <view class="adressLine">
          <view class="lable-L">收货人</view>
          <input v-model="addressData.name" class="input" type="text" placeholder="请输入收货人" placeholder-class="placeholder" @blur="btnFixed()" />
        </view>
        <view class="adressLine">
          <view class="lable-L">配送地址</view>
          <text class="input" :class="{'input-none': !addressData.province}" @tap="toggleTab()">{{ addressData.province ? addressData.areaName : '请选择省市区' }}</text>
          <image src="/static/images/mine/ic_mine_arror.png" class="ic_mine_arror" />
        </view>
        <view class="adressLine">
          <view class="lable-L">详细地址</view>
          <input v-model="addressData.detail" class="input" type="text" placeholder="请填写详细地址（街道、楼牌号等）" placeholder-class="placeholder" @blur="btnFixed()" />
        </view>
      </view>
    </view>
    <view class="goods">
      <view class="goods_content">
        <view class="image_box">
          <b-image :src="goodsDetail.pic" :width="140" :height="140" />
        </view>
        <view class="goods_info">
          <view class="goods_title">{{ goodsDetail.title }}</view>
          <view class="goods_sku">{{ goodsDetail.sku_list[0].properties_name }}</view>
          <view class="goods_price">￥{{ goodsDetail.price }}</view>
        </view>
        <view class="goods_num">
          x1
        </view>
      </view>
      <view class="remark">
        <view>留言说明：</view>
        <input v-model="remark" class="input" type="text" placeholder="您对本次交易的说明" placeholder-class="placeholder" />
      </view>
    </view>
    <view class="price_all">
      <view class="price_info">
        <view>商品金额</view>
        <view>￥{{ goodsDetail.vip_price }}</view>
      </view>
      <view class="price_info red">
        <view>邮费</view>
        <view>包邮</view>
      </view>
      <view class="price_info">
        <view>合计</view>
        <view>￥{{ goodsDetail.vip_price }}</view>
      </view>
    </view>
    <view class="bottomFix">
      <view class="bottomBox">
        <view>合计金额：<text class="price">￥{{ goodsDetail.vip_price }}</text></view>
        <view class="payBtn" :class="{'disable': soldOutList}" @click="showPay">去付款</view>
      </view>
    </view>
    <address-picker
      :show="showAddressPicker"
      key-str="name"
      :default-data="[addressData.province,addressData.city,addressData.area]"
      @close="showAddressPicker = false"
      @confirm="onConfirm" />
    <pay-dialog
      ref="payDialog"
      :order-no="order_no"
      :form-type="260"
      @submitCallBack="toPayResult"
      @close="close"></pay-dialog>
  </base-page-view>
</template>
<script>
import './orderCheck.scss'
import addressPicker from '../components/address-picker/index.vue'
import payDialog from '../components/payDialog'
export default {
  components: {
    addressPicker,
    payDialog
  },
  data() {
    return {
      showAddressPicker: false,
      soldOutList: false,
      getVerify: '获取验证码',
      addressData: {
        name: '',
        mobile: '',
        province: '',
        city: '',
        area: '',
        country: '中国',
        detail: '',
        areaName: '',
        is_default: false
      },
      remark: '',
      invite_code: '',
      address_id: '',
      order_no: '',
      goodsId: '',
      goodsDetail: {}
    }
  },
  created() {
    this.getupgradeMakeMoneyMemberGoods()
  },
  onLoad() {
    if (uni.getStorageSync('s_addressData')) {
      this.addressData = JSON.parse(uni.getStorageSync('s_addressData'))
      this.addressData.code = ''
    }
  },
  onShow() {
    const invite_code = uni.getStorageSync('share_code')
    console.log('invite_code', invite_code)
    if (invite_code) {
      this.invite_code = invite_code
    }
  },
  methods: {
    verify() {
      if (this.getVerify !== '获取验证码') {
        return
      }
      if (!(/^\d{11}$/.test(this.addressData.mobile.replace(/\s*/g, '')))) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none',
          duration: 2 * 1000
        })
      } else {
        this.subcli()
      }
    },
    async subcli() {
      const res = await this.$api.loginApi.sendSms('+86', this.addressData.mobile.replace(/\s*/g, ''))
      if (res.code) {
        return
      }
      uni.showToast({
        title: '短信发送成功，请注意查收！',
        icon: 'none',
        duration: 2 * 1000
      })
      this.value = 60
      this.getVerify = this.value + 's'

      var timers = setInterval(() => {
        this.value--
        this.getVerify = this.value + 's'
        if (this.value <= 0) {
          clearInterval(timers)
          this.getVerify = '获取验证码'
        }
      }, 1000)
    },
    // 获取升级赚钱商品
    async getupgradeMakeMoneyMemberGoods() {
      const res = await this.$api.promotionApi.getUpgradeMakeMoneyMemberGoods({
        upgradeMakeMoneyMemberId: 4
      })
      if (res.code) {
        return
      }
      this.goodsId = res.data.upgradeGoodsList[0].goodsId
      this.getGoodsDetail()
    },
    // 获取升级赚钱商品详情
    async getGoodsDetail() {
      const res = await this.$api.goodsApi.goodsDetail({
        goods_id: this.goodsId,
        from_type: 260,
        goods_type: 1
      })
      if (res.code) {
        return
      }
      this.goodsDetail = {
        ...res.data.goods,
        sku_code: res.data.goods.sku_list[0].sku_code,
        vip_price: Number(res.data.goods.vip_price).toFixed(2),
        num: 1,
        from_type: 260
      }
    },
    toggleTab() {
      this.showAddressPicker = true
    },
    onConfirm(data) {
      this.addressData.areaName = data[0].name + data[1].name + data[2].name
      this.addressData.province = data[0].name
      this.addressData.city = data[1].name
      this.addressData.area = data[2].name
      this.btnFixed()
      this.showAddressPicker = false
    },
    // 去支付
    async showPay() {
      this.$sensorTrack('CLICKBUTTON', {
        page_name: 'order_confirmation',
        button_name: 'wx_pay'
      })

      if (!(/^\d{8,11}$/.test(this.addressData.mobile.replace(/\s*/g, '')))) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return
      }
      if (this.addressData.code.length !== 6) {
        uni.showToast({
          title: '请输入正确的验证码',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return
      }
      if (!this.addressData.areaName) {
        uni.showToast({
          title: '请选择省、市、区',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return
      }
      if (!this.addressData.detail) {
        uni.showToast({
          title: '请输入详细地址',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return
      }
      if (this.soldOutList) {
        return
      }
      this.loginMobile()
    },
    async loginMobile() {
      this.soldOutList = true
      const login = {
        region_code: '+86',
        mobile: this.addressData.mobile.replace(/\s*/g, ''),
        sms_code: this.addressData.code
      }
      const response = await this.$api.loginApi.mobileLogin(login)
      if (response.code) {
        this.soldOutList = false
        return
      }
      this.$store.dispatch('SET_USER', {
        token: response.data.token,
        userInfo: response.data.user
      })
      this.addaddress()
    },
    // 添加地址
    async addaddress() {
      const res = await this.$api.mineApi.addShippingAddress(this.addressData)
      if (res.code) {
        this.soldOutList = false
        return
      }
      this.address_id = res.data.address_id
      this.addOrder()
      this.soldOutList = false
    },
    // 下单
    async addOrder(type) {
      if (this.order_no) {
        this.$refs.payDialog.show()
        this.soldOutList = false
        return false
      }
      var shoppingList = JSON.stringify(
        [{
          goods_id: this.goodsDetail.goods_id,
          goods_type: this.goodsDetail.type,
          sku_code: this.goodsDetail.sku_code,
          num: this.goodsDetail.num,
          from_type: this.goodsDetail.from_type
        }])
      const data = {
        shopping_list: shoppingList,
        shipping_address_id: this.address_id,
        remark: this.remark
      }
      // 如果有邀请码，则将邀请码一起写进去
      if (this.invite_code) {
        data.inviteCode = this.invite_code
      }
      const res = await this.$api.orderApi.orderAdd(data)

      if (res.code) {
        return false
      }
      this.order_no = res.data.order_no
      this.$refs.payDialog.show()
      return true
    },
    // 支付结果
    toPayResult(data) {
      // #ifdef H5
      const type = data.type
      if (type === '2') {
        // h5支付
        let wechatUrl = data.url
        wechatUrl += `&redirect_url=${encodeURIComponent(location.origin + '/pagesOrder/orderSuccess/index?orderNo=' + this.order_no)}`
        location.href = wechatUrl
      } else if (type === '3') {
        // let wechatUrl = ''
        uni.setStorageSync('__success_return__', {
          url: location.href,
          orderNo: this.order_no
        })
        // wechatUrl = `${encodeURIComponent(location.origin + '/pagesOrder/orderSuccess/H5ResultGet?orderNo=' + this.order_no)}`
      }
      // #endif

      // #ifdef MP-WEIXIN
      this.$navigateTo('/pagesOrder/orderSuccess/index?orderNo=' + this.order_no, '', 'redirectTo')
      // #endif
    },
    // 未支付
    close() {
      // this.$navigateTo('/pagesOrder/promotion/orderCheck', '', 'redirectTo')
      this.$refs.payDialog.hide()
    },
    btnFixed() {
      const jsonData = {
        ...this.addressData
      }
      delete jsonData.code
      uni.setStorageSync('s_addressData', JSON.stringify(jsonData))
      uni.pageScrollTo({ scrollTop: 0 })
    }
  }
}
</script>
